package com.example.apiproject.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.apiproject.dao.UserDao;
import com.example.apiproject.entity.Labels;
import com.example.apiproject.entity.User;
import com.example.apiproject.entity.form.LoginForm;
import com.example.apiproject.jwt.jwtutil;
import com.example.apiproject.service.OssService;
import com.example.apiproject.service.UserService;
import com.example.apiproject.utils.R;
import com.example.apiproject.utils.Res;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;

import okhttp3.Response;
/**
 * (User)表控制层
 *
 * @author makejava
 * @since 2023-09-23 13:40:57
 */
@RestController
@RequestMapping("/user")
public class UserController {
    /**
     * 服务对象
     */
    @Autowired
    private UserService userService;

    @Autowired
    private jwtutil jwtUtils;
    @Autowired
    private OssService ossservice;
    @Autowired
    private UserDao userdao;

    /**
     * 实名认证
      */
    @PostMapping("/IDArrestation")
    public R IDArestation(String name,String ID) throws IOException{
        String url = "https://idenauthen.market.alicloudapi.com/idenAuthentication";
        // 获取appCode链接：https://market.console.aliyun.com/

        String appcode = "6da33fca7dc94774b288159115c77281";

        String result = "";
        FormBody formBody = new FormBody.Builder().add("name", name).add("idNo", ID).build();
        Request request = new Request.Builder().url(url).addHeader("Authorization", "APPCODE " + appcode).post(formBody).build();

        Call call = new OkHttpClient().newCall(request);
        Response response = null;
        try {
            response = call.execute();
        } catch (IOException e) {
            System.out.println("execute failed, message:" + e.getMessage());
        }

        assert response != null;
        if (!response.isSuccessful()) {      // 当返回结果发生错误时
            // 状态码为403时一般是套餐包用尽，需续购；注意：续购不会改变秘钥（appCode），仅增加次数
            // 续购链接：https://market.aliyun.com/products/57000002/cmapi025518.html
            System.out.println("request failed----" + "返回状态码" + response.code()  + ",message:" + response.message());
        }
        result = response.body().string();    //此处不可以使用toString()方法，该方法已过期
        JSONObject jsonObject =  JSON.parseObject(result);
        return R.ok().put("result",jsonObject);
    }



    /**
     * 添加标签
     * 测试用例
     * {
     *     "labelNames": ["Sports", "Music", "Food"]
     * }
     */
    @PostMapping("/addlabels/{userId}")
    public ResponseEntity<User> addUserLabels(
            @PathVariable int userId,
            @RequestBody Map<String, List<String>> request
    ) {
        List<String> labelNames = request.get("labelNames");
        return ResponseEntity.ok(this.userService.addUserLabel(userId, labelNames));
    }

    //删除标签
    @PostMapping("/delete/{userId}/labels/{labelId}")
    public R deleteUserLabel(@PathVariable("userId") int userId, @PathVariable("labelId") int labelId) {
        int total = userService.deleteUserLabel(userId, labelId);
        if (total == 0)
            return R.error("删除失败");
        return R.ok("删除成功");
    }


    @PostMapping("/smsLogin")
    @ApiOperation("手机密码登录")
    public R smsLogin(@RequestBody LoginForm form) {

        //用户登录
        Integer userId = userService.login(form);
        if (userId == null)
            return R.error("未注册");
        //生成token
        String token = jwtUtils.createToken(userId);

        Map<String, Object> map = new HashMap<>();
        map.put("token", token);


        return R.ok(map);
    }

    @PostMapping("/login")
    @ApiOperation("用户名或手机，密码登录")
    public Res login(@RequestBody LoginForm form) {
        //用户登录
        User user = userService.findUser(form);
        if (user == null)
            return Res.failure("未注册");
        else if (!user.getPassword().equals(form.getPassword())) {
            return Res.failure("密码错误");
        }
        //生成token
//        String token = jwtUtils.createToken(user.getId());
//
//        Map<String, Object> map = new HashMap<>();
//        map.put("token", token);

        return Res.ok(user);
    }

    @PostMapping("/register")
    public R register(@RequestBody User form) {

        if (userdao.selectbyphone(form.getPhone()) == 1)
            return R.error("该手机号已注册");
        int id = userService.register(form);
        if (id == 0)
            return R.error("注册失败");
        return R.ok("注册成功");
    }

    @GetMapping("userInfo")
    public R userInfo(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            token = request.getParameter("token");
        }
//
        int userId = jwtUtils.getUserId(token);

        User user = userdao.queryById(userId);
        if (user == null) return R.error("异常");

        return R.ok("查询成功").put("result", user);
    }

    /**
     * 分页查询
     *
     * @param user        筛选条件
     * @param pageRequest 分页对象
     * @return 查询结果
     */
    @GetMapping
    public ResponseEntity<Page<User>> queryByPage(User user, PageRequest pageRequest) {
        return ResponseEntity.ok(this.userService.queryByPage(user, pageRequest));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public R queryById(@PathVariable("id") Integer id) {
        return R.ok().put("data", this.userService.queryById(id));
    }

    /**
     * 新增数据
     *
     * @param user 实体
     * @return 新增结果
     */
    @PostMapping
    public ResponseEntity<User> add(User user) {
        return ResponseEntity.ok(this.userService.insert(user));
    }

    @PostMapping("/update")
    public R update(@RequestBody User user) {
        int number = userService.update(user);
        if (number == 1) return R.ok();
        return R.error();
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping
    public ResponseEntity<Boolean> deleteById(Integer id) {
        return ResponseEntity.ok(this.userService.deleteById(id));
    }

//    @GetMapping("/labels/{lid}")
//    public User getUserWithLabels(@PathVariable("lid") int id) {
//        return userService.getUserWithLabels(id);
//    }

}

